<?php
declare (strict_types = 1);

namespace app\api\controller;

use app\admin\model\erp\ErpAdverts;
use app\admin\model\erp\ErpAdvertsLogs;
use bbweb\basic\BaseController;
use think\facade\Db;
use think\Request;

class Advert extends BaseController
{
    /**
     * 广告接口
     * @param  \think\Request  $req
     * @return \think\Response
     */
    public function getAdvert(Request $req)
    {
        $timestamp = $req->param('timestamp/d',0);
        $sign = $req->param('sign','');
        $data = $req->param('data',[]);

        $secret_key = 'sDFajhsDSjsaTq2w';
        $time = time();
        if(empty($sign) || !$timestamp) return 'error_1';
        if($time > $timestamp + 5) return 'error_2';
        if( md5(md5($secret_key) . $timestamp ) != $sign ) return 'error_3';
        $advert = ErpAdverts::where('scene',1)->where('start_at', '<=', $time)->where('end_at', '>=', $time)->where('status', 1)->order('total ASC')->find();
        if(!$advert) return 'error_4';
        ErpAdverts::where('id', $advert['id'])->update(['total'=>Db::raw('total+1')]);
        ErpAdvertsLogs::create(['aid'=>$advert['id'],'data'=>$data,'create_at'=>$time]);
        return json(['times'=>$advert['times'],'url'=>$advert['url'], 'imgs'=>set_file_url($advert['imgs'], 'http://api.cklock.cn')]);
    }
}
